<template>
  <div class="boxs">
    <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
    >
      <el-form-item label="" prop="skuName">
        <el-input
            v-model="queryParams.skuName"
            placeholder="请输入赠品名称"
            clearable
            size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
        >搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" type="primary"  size="small" @click="openDialog">添加赠品</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" style="margin-top: 15px" v-loading="loading">
      <el-table-column label="ID" align="center" min-width="60" prop="id" />
      <el-table-column label="赠品名称" align="center" min-width="120" prop="skuName" />
      <el-table-column label="封面图" align="center" min-width="100" prop="imgUrl">
        <template  slot-scope="scope">
          <img style="width:80px;height:80px;border:none;" :src="scope.row.imgUrl" v-if="scope.row.imgUrl">
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="赠品类型" align="center" min-width="120" prop="gift_level">
        <template slot-scope="scope">
          {{ scope.row.gift_level == 1 ? '满49元赠5' : '满99元赠10' }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" :formatter="formatterCreateTime"  min-width="140"/>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button size="mini"  @click="handleEdit(scope.row)"  type="primary">编辑</el-button>
          <el-button size="mini"  @click="del(scope.row.id)"  type="danger" v-if="!scope.row.discountType">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getGift"
    />

    <el-dialog title="赠品信息" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
      <el-form  class="demo-form-inline" label-width="100px" :model="form" :rules="rules" ref="ruleForm" :inline="true">
        <!-- <el-form-item label="商品ID" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="商品编码" prop="skuCode">
          <el-input v-model="form.skuCode" placeholder="请输入商品编码" />
        </el-form-item> -->
        <el-form-item label="赠品" prop="product_id">
          <el-select v-model="form.product_id" placeholder="请选择赠品" @change="handleProductChange">
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.skuName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赠品名称" prop="skuName" >
          <el-input v-model="form.skuName" placeholder="请输入赠品名称" style="width:220px"/>
        </el-form-item>
        <el-form-item label="赠品图片" prop="skuName" >
           <img style="width:80px;height:80px;border:none;" :src="form.imgUrl" v-if="form.imgUrl">
        </el-form-item>
        <el-form-item label="赠品等级" prop="gift_level">
          <el-select v-model="form.gift_level" placeholder="请选择赠品等级">
            <el-option label="满49元赠5" :value="1"></el-option>
            <el-option label="满99元赠10" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-loading="addLoading">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="form.id ? 'warning' : 'primary'" @click="affirm">{{
            form.id ? "确认修改" : "确认添加"
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imgdialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {getGift,upGift,addGift,delGift,getProductSelect} from "@/api/admin";
import {formatDate} from "@/utils";
export default {
  name: "Gift",
  data(){
    return {
      productList:[],
      



      imgdialogVisible:false,
      dialogImageUrl:'',
      id: this.$store.getters.id,
      queryParams:{
        page:1,
        size:10,
        skuName:'',
        isCoupon:0,
      },
      total:0,
      loading:false,
      addLoading:false,
      list:[],
      dialogVisible:false,
      form:{},
      rules:{
        skuName:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        type:[{ required: true, message: '请选择分类', trigger: 'change' }],
        price:[
          { required: true, message: '请输入销售价', trigger: 'blur' },
        ],
        orinprice:[
          { required: true, message: '请输入划线价', trigger: 'blur' },
        ],
        inventory:[
          { required: true, message: '请输入库存', trigger: 'blur' },
          { validator: this.validateInteger, trigger: 'blur' }
        ],
        // detailJson:[
        //   { required: true, message: '请输入商品说明', trigger: 'blur' },
        // ],
      },

      
    }
  },
  created() {
    this.getGift();
  },
  methods:{
    openDialog () {
      this.resetForm();
      this.getProductSelect();
      this.dialogVisible = true
    },
    async getProductSelect(){
      let {data}=await getProductSelect();
      console.log(123456,data);
      this.productList=data;
    },
    async getGift(){
      let {data}=await getGift(this.queryParams);
      console.log(123456,data);
      this.list=data.list;
      this.total=data.total;
    },
    resetForm () {
      this.form = {};
    },
    del(id){
        this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delGift({id:id});
          this.getGift();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });

        }).catch(() => {
           
        });
      },
    affirm(){
      this.$refs['ruleForm'].validate(async (valid) => {
        if (!valid) return;
        try {
          if(this.fileList.length==0){
            this.$message.error("请上传封面！");
            return;
          }else{
            let imgUrl=await this.finish();
              if(imgUrl){
                this.form.imgUrl=imgUrl;
              }
          }

          if(this.form.id){
            this.form.imgDetails=await this.finish2();
            console.log(1,this.form.imgDetails);
             console.log(2,this.fileData2);
             console.log(3,this.fileList2);
             let oldUrl=this.fileList2.filter(f => !f.raw ).map(obj => obj.url);
             this.form.imgDetails=oldUrl.concat(this.form.imgDetails);
             console.log(4,this.form.imgDetails);
          }else{
            this.form.imgDetails=await this.finish2();
          }
         
          this.addLoading=true;
          this.form.isCoupon=0;
          !this.form.id&& await addGift(this.form);
          this.form.id&&  await upGift(this.form);
          this.addLoading=false;
          this.$message.success(this.form.id?'修改成功！':'添加成功！');
          this.getGift();
          this.dialogVisible = false;
        }catch (e) {
          this.addLoading=false;
        }

      });
    },
    
    handleQuery(){
      this.queryParams.page=1;
      this.getGift();
    },
    handleEdit(row){
      console.log(999,row.type);
      if(!Array.isArray(row.type)){
        row.type=row.type.split(',')
      }
      this.form={...row};
      this.fileList=[
        {
          name:this.form.imgUrl.replace('https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/','').split('-').pop(),
          url:this.form.imgUrl
        }
      ];
      this.fileList2=[]
      let _this=this;
      if(this.form.imgDetails){
        this.form.imgDetails.split(',').forEach(function(img) {
              _this.fileList2.push({
                name:img.replace('https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/','').split('-').pop(),
                url:img
              })
          });
      }
      
      console.log(555,this.fileList2);
      this.dialogVisible=true;
      this.$refs['ruleForm'].clearValidate(); 
    },
    formatterCreateTime(row){
      return formatDate(row.updateTime);
    }
  }
}
</script>

<style scoped>
  .ql-container {
    min-height: 300px;
  }
</style>
